package aeemqx

import (
	"context"
	v1 "devops-super/api/configs/v1"
	"devops-super/internal/consts"
	"devops-super/internal/consts/cacheConsts"
	"devops-super/internal/model/entity"
	"devops-super/internal/model/mymodel"
	"devops-super/internal/service"
	"devops-super/pb"
	"encoding/json"
	"errors"
	"github.com/gogf/gf/v2/os/gtime"
	"strconv"
	"strings"
)

func (s *sAeemqx) addOrUpdConfig(ctx context.Context, deviceNo string, configKey string, configVal string) (err error) {
	configRes, _ := service.DeviceConfig().GetConfig(ctx, &v1.GetDeviceConfigReq{
		DeviceNo:  deviceNo,
		ConfigKey: configKey,
	})
	updata := new(entity.AppDeviceConfig)
	updata.DeviceNo = deviceNo
	updata.ConfigKey = configKey
	updata.ConfigValue = configVal
	updata.UpdatedAt = gtime.Now()
	if configRes.Id > 0 {
		updata.Id = configRes.Id
		err = service.DeviceConfig().Upt(ctx, updata)
		if err != nil {
			return err
		}
	} else {
		updata.CreatedAt = gtime.Now()
		err = service.DeviceConfig().Add(ctx, updata)
		if err != nil {
			return err
		}
	}
	// 确保缓存更新 删掉缓存
	cacheKey := cacheConsts.GetDeviceConfigKey(deviceNo, configKey)
	_, _ = service.GetCacheInstance().Remove(ctx, cacheKey)
	return
}

func (s *sAeemqx) implementHandleAeMeasureConfig(ctx context.Context, deviceNo string, aeMeasureConfig *pb.AeMeasureConfig) (err error) {
	var configKey = consts.DeviceConfTypeParamConfig
	if aeMeasureConfig == nil {
		err = errors.New("config is nil")
		return err
	}
	modelData := &mymodel.AeParamConfItem{
		AeEet:             int(aeMeasureConfig.GetAeEet()),
		AeHdt:             int(aeMeasureConfig.GetAeHdt()),
		AeHlt:             int(aeMeasureConfig.GetAeHlt()),
		AeThreshold:       int(aeMeasureConfig.GetAeThreshold()),
		AeParaEnable:      aeMeasureConfig.GetAeParaEnable(),
		AeSystemTime:      int(aeMeasureConfig.GetAeSystemTime()),
		AeWaveEnable:      aeMeasureConfig.GetAeWaveEnable(),
		AeMeasureMode:     int(aeMeasureConfig.GetAeMeasureMode()),
		AeMeasureSpeed:    int(aeMeasureConfig.GetAeMeasureSpeed()),
		AeMeasureState:    aeMeasureConfig.GetAeMeasureState(),
		AeMeasureTimes:    int(aeMeasureConfig.GetAeMeasureTimes()),
		AeMeasureLength:   int(aeMeasureConfig.GetAeMeasureLength()),
		AeMeasureInterval: int(aeMeasureConfig.GetAeMeasureInterval()),
	}
	_jsonByte, err := json.Marshal(modelData)
	if err != nil {
		return err
	}
	jsonstr := string(_jsonByte)
	err = s.addOrUpdConfig(ctx, deviceNo, configKey, jsonstr)
	return
}

func (s *sAeemqx) implementHandleAeFFTConfig(ctx context.Context, deviceNo string, aeconfig *pb.AeFFTConfig) (err error) {
	var configKey = consts.DeviceConfTypeAeFftConfig
	if aeconfig == nil {
		err = errors.New("config is nil")
		return err
	}
	bandItems := make([]*mymodel.AeFFTConfBandItem, 0)
	if aeconfig.AeFFTConfigBandItems != nil {
		for _, band := range aeconfig.AeFFTConfigBandItems {
			bandItems = append(bandItems, &mymodel.AeFFTConfBandItem{
				Index:  band.Index,
				Start:  band.Start,
				End:    band.End,
				Enable: band.Enable,
			})
		}
	}
	var configModel = &mymodel.AeFFTConfItem{
		AeFftEnable:          aeconfig.AeFftEnable,
		AeFFTConfigBandItems: bandItems,
		Extract:              aeconfig.Extract,
	}
	_jsonByte, err := json.Marshal(configModel)
	if err != nil {
		return err
	}
	jsonstr := string(_jsonByte)
	err = s.addOrUpdConfig(ctx, deviceNo, configKey, jsonstr)
	return
}

func (s *sAeemqx) implementHandleAeTimingConfig(ctx context.Context, deviceNo string, aeconfig *pb.AeTimingConfig) (err error) {
	var configKey = consts.DeviceConfTypeTimingConfig
	if aeconfig == nil {
		err = errors.New("config is nil")
		return err
	}
	modelData := &mymodel.AeTimingConfItem{
		AeTimingType:      int(aeconfig.GetAeTimingType()),
		AeTimingSleep:     int(aeconfig.GetAeTimingSleep()),
		AeTimingEnable:    aeconfig.GetAeTimingEnable(),
		AeTimingLength:    int(aeconfig.GetAeTimingLength()),
		AeFixedTimingList: make([]*mymodel.AeFixedTimingListItem, 0),
		Crons:             make([]*mymodel.AeCronItem, 0),
	}
	if aeconfig.GetAeTimingType() == 5 {
		cronList := make([]*mymodel.AeCronItem, 0)
		getCrons := aeconfig.GetCrons()
		if getCrons != nil {
			for _, item := range getCrons {
				cronList = append(cronList, &mymodel.AeCronItem{
					Start: item.Start,
					End:   item.End,
					Cron:  item.Cron,
				})
			}
		}
		modelData.Crons = cronList
	}
	// 定时配置 多份固定时间段
	if aeconfig.GetAeTimingType() == 2 {
		timingList := make([]*mymodel.AeFixedTimingListItem, 0)
		timer := aeconfig.GetAeTimer()
		if timer != nil {
			starts := strings.Split(timer.GetAeTimingStart(), ",")
			ends := strings.Split(timer.GetAeTimingStop(), ",")
			for i := 0; i < int(timer.AeTimingIndexMax); i++ {
				ranges := make([]int, 0)
				start0, err := strconv.Atoi(starts[i])
				if err != nil {
					return err
				}
				end0, err := strconv.Atoi(ends[i])
				if err != nil {
					return err
				}
				ranges = append(ranges, start0, end0)
				titem := new(mymodel.AeFixedTimingListItem)
				titem.Range = ranges
				timingList = append(timingList, titem)
			}
		}
		modelData.AeFixedTimingList = timingList
	}

	_jsonByte, err := json.Marshal(modelData)
	if err != nil {
		return err
	}
	jsonstr := string(_jsonByte)
	err = s.addOrUpdConfig(ctx, deviceNo, configKey, jsonstr)
	return
}

// v2版本 评级配置
func (s *sAeemqx) implementHandleLevelConfig(ctx context.Context, deviceNo string, config *pb.LevelConfig) (err error) {
	var configKey = consts.DeviceConfTypeLevelConfig2
	if config == nil {
		err = errors.New("config is nil")
		return err
	}
	aestrength := make([]*mymodel.AeLevelStrength, 0)
	if config.GetAeLevelStrength() != nil {
		for _, item1 := range config.GetAeLevelStrength() {
			thisaestrength := new(mymodel.AeLevelStrength)
			tmpRules := make([]*mymodel.AeLevelRule, 0)
			if item1.GetRules() != nil {
				for _, item2 := range item1.GetRules() {
					thisrule := new(mymodel.AeLevelRule)
					tmpProps := make([]*mymodel.AeLevelRuleItem, 0)
					if item2.GetItems() != nil {
						for _, item3 := range item2.GetItems() {
							tmpProps = append(tmpProps, &mymodel.AeLevelRuleItem{
								Prop:  item3.GetProp(),
								Value: item3.GetValue(),
							})
						}
					}
					thisrule.Items = tmpProps
					tmpRules = append(tmpRules, thisrule)
				}
			}
			thisaestrength.Level = int(item1.Level)
			thisaestrength.Rules = tmpRules
			aestrength = append(aestrength, thisaestrength)
		}
	}
	aeactivity := make([]*mymodel.AeLevelActivity, 0)
	if config.GetAeLevelActivity() != nil {
		for _, item1 := range config.GetAeLevelActivity() {
			aeactivity = append(aeactivity, &mymodel.AeLevelActivity{
				Level: int(item1.Level),
				Times: int(item1.Times),
			})
		}
	}

	modelData := &mymodel.AeLevelConfItem2{
		Enable:          config.Enable,
		AeLevelStrength: aestrength,
		AeLevelActivity: aeactivity,
		CalTime:         int(config.CalTime),
		ReportLevel:     int(config.ReportLevel),
		Interval:        int(config.Interval),
	}

	_jsonByte, err := json.Marshal(modelData)
	if err != nil {
		return err
	}
	jsonstr := string(_jsonByte)
	err = s.addOrUpdConfig(ctx, deviceNo, configKey, jsonstr)
	return
}

func (s *sAeemqx) implementHandleAeFirConfig(ctx context.Context, deviceNo string, config *pb.FirConfig) (err error) {
	var configKey = consts.DeviceConfTypeFirConfig
	if config == nil {
		err = errors.New("config is nil")
		return err
	}
	modelData := &mymodel.AeFirConfItem{
		FirLow:    int(config.GetFirLow()),
		FirHigh:   int(config.GetFirHigh()),
		FirEnable: int(config.GetFirEnable()),
		FirM2Mode: int(config.GetFirM2Mode()),
	}
	_jsonByte, err := json.Marshal(modelData)
	if err != nil {
		return err
	}
	jsonstr := string(_jsonByte)
	err = s.addOrUpdConfig(ctx, deviceNo, configKey, jsonstr)
	return
}

func (s *sAeemqx) implementHandleViMeasureConfig(ctx context.Context, deviceNo string, config *pb.ViMeasureConfig) (err error) {
	var configKey = consts.DeviceConfTypeViMeasureConfig
	if config == nil {
		err = errors.New("config is nil")
		return err
	}
	confdata := &mymodel.ViMeasureConfItem{
		ViMeasureType:       config.ViMeasureType,
		ViMeasureFreq:       config.ViMeasureFreq,
		ViMeasureTimes:      config.ViMeasureTimes,
		ViMeasurePoints:     config.ViMeasurePoints,
		ViMeasureSleep:      config.ViMeasureSleep,
		ViFirLow:            config.ViFirLow,
		ViFirHigh:           config.ViFirHigh,
		ViFirAmp:            config.ViFirAmp,
		ViOffsetX:           float32(config.ViOffsetX),
		ViOffsetY:           float32(config.ViOffsetY),
		ViOffsetZ:           float32(config.ViOffsetZ),
		ViFactorX:           float32(config.ViFactorX),
		ViFactorY:           float32(config.ViFactorY),
		ViFactorZ:           float32(config.ViFactorZ),
		ViRange:             config.ViRange,
		ViWaveEnable:        config.ViWaveEnable,
		ViMeasureState:      config.ViMeasureState,
		ViSystemTime:        config.ViSystemTime,
		ViConfigVersion:     config.ViConfigVersion,
		ViSaveLoop:          config.ViSaveLoop,
		ViOffsetTemperature: float32(config.ViOffsetTemperature),
		ViRemoveAccX:        config.ViRemoveAccX,
		ViRemoveAccY:        config.ViRemoveAccY,
		ViRemoveAccZ:        config.ViRemoveAccZ,
	}
	_jsonByte, err := json.Marshal(confdata)
	if err != nil {
		return
	}
	jsonstr := string(_jsonByte)
	err = s.addOrUpdConfig(ctx, deviceNo, configKey, jsonstr)
	return
}

func (s *sAeemqx) implementHandleFrpConfig(ctx context.Context, deviceNo string, config *pb.FrpConfig) (err error) {
	var configKey = consts.DeviceConfTypeFrpConfig
	if config == nil {
		err = errors.New("config is nil")
		return err
	}
	updatedata := &mymodel.AeFrpItem{
		Enable:               config.Enable,
		ServerIp:             config.ServerIp,
		ServerPort:           config.ServerPort,
		RemotePort:           config.RemotePort,
		TcpMux:               config.TcpMux,
		TcpMuxConnectTimeout: config.TcpMuxConnectTimeout,
		HeartbeatInterval:    config.HeartbeatInterval,
		HeartbeatTimeout:     config.HeartbeatTimeout,
	}
	_jsonByte, err := json.Marshal(updatedata)
	if err != nil {
		return
	}
	jsonstr := string(_jsonByte)
	err = s.addOrUpdConfig(ctx, deviceNo, configKey, jsonstr)
	return
}
